import { GenTableColumnEntity } from '../../entities/gen-table-cloumn.entity';

export const dialogVue = (options: any) => {
  const html = getFormHtmlStr(options.columns);
  const script = generateScriptSetup(options);
  return `
    ${script}
    ${html}
    <style lang="scss" scoped></style>
  `;
};

// 获取表单自定义插槽内容
const getFormSlotHtmlStr = (columns: GenTableColumnEntity[]) => {
  const filterColumn = columns.filter((item) => {
    return item.isInsert === '1' && ['imageUpload', 'fileUpload', 'editor'].includes(item.htmlType);
  });
  let htmlStr = ``;
  filterColumn.forEach((item) => {
    let comStr = '';
    if (item.htmlType === 'editor') {
      comStr = `<editor v-model="gFormData.${item.javaField}" />`;
    }
    if (item.htmlType === 'fileUpload') {
      comStr = `<file-upload v-model="gFormData.${item.javaField}" />`;
    }
    if (item.htmlType === 'imageUpload') {
      comStr = `<image-upload v-model="gFormData.${item.javaField}" />`;
    }
    htmlStr += ` 
        <template #plus-field-${item.javaField}>
            ${comStr}
        </template>
    `;
  });
  return htmlStr;
};

// 获取表单模板
const getFormHtmlStr = (columns: GenTableColumnEntity[]) => {
  const formSlotHtmlStr = getFormSlotHtmlStr(columns);
  return `
    <template>
      <PlusDialog v-model="gVisible" v-bind="gDialogConfig">
        <PlusForm ref="gFormInstance" v-model="gFormData" :columns="columns" v-bind="gFormConfig">
         ${formSlotHtmlStr}
        </PlusForm>
      </PlusDialog>
    </template>
  `;
};

const generateFormData = (columns: any[]) => {
  return columns
    .filter((item) => item.isInsert === '1' && item.isPk === '0')
    .map((item) => `${item.javaField}: ${item.htmlType === 'checkbox' ? '[]' : '""'}`)
    .join(',\n');
};

//  生成验证规则
const generateRulesData = (columns: any[]) => {
  return columns
    .filter((item) => item.isRequired === '1')
    .map((item) => {
      let trigger = '"blur"';
      if (['select', 'radio', 'checkbox'].includes(item.htmlType)) {
        trigger += ',"change"';
      }
      return `${item.javaField}: [{ required: true, message: "${item.columnComment}不能为空", trigger: [${trigger}] }]`;
    })
    .join(',\n');
};

const generateScriptSetup = ({ columns }) => {
  const formStr = generateFormData(columns);
  const rulesStr = generateRulesData(columns);

  return `
    <script setup>
    import { useAddEditHook } from '@/hooks/crud/index.js'
    import { useColumnsDict, useCommonConfig } from './hook.js'
    import { useFormConfigHook } from '@/hooks/usePlusConfigHook.js'
    const { proxy,  primaryKey,apiFn, moduleName } = useCommonConfig()
    const emit = defineEmits(['refreshList'])
    
    // 表单初始化数据
    const initForm = {
      ${formStr}
    }
    const rules = {
      ${rulesStr}
    }
    
    // 钩子函数
    const handlerConfig = {
      beforeOpenFn: (data) => {
      },
      afterOpenFn: (resData) => {
      },
      beforeInfoFn: (reqData) => {
        return reqData[[primaryKey]]
      },
      afterInfoFn: (resData) => {
        return resData
      },
      beforeSubmitFn: (reqData) => {
        return reqData
      },
      afterSubmitFn: (resData) => {
        emit('refreshList')
        return resData
      },
      beforeCloseFn: () => true,
      afterCloseFn: () => {}
    }
    
    const { gOpen, gAllExposeOption,gVisible,gFormInstance,gFormData, gIsEdit  } = useAddEditHook({
      moduleName,
      primaryKey,
      initForm,
      rules,
      apiFnConfig:apiFn.apiFnConfig,
      handlerConfig
    })
    
    const { gDialogConfig,  gFormConfig} = useFormConfigHook(gAllExposeOption,{
      dialogConfig:{},
      formConfig:{}
    });
    const {  dictData,  columns, } = useColumnsDict(true,gFormData);
    // 暴露
    defineExpose({ gOpen })
    </script>
  `;
};
